package com.github.ilioili.justdoit.components.fragment;

import android.animation.ArgbEvaluator;
import android.graphics.Color;
import android.support.annotation.NonNull;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;

import com.github.ilioili.justdoit.components.activity.MainActivity;
import com.github.ilioili.justdoit.R;
import com.github.ilioili.justdoit.model.dao.ScheduleEventDao;
import com.github.ilioili.justdoit.model.pojo.ScheduleEvent;
import com.github.ilioili.justdoit.util.sql.SqlCallback;
import com.taihe.template.base.BaseFragment;
import com.taihe.template.base.injection.Id;
import com.taihe.template.base.injection.Layout;

import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

/**
 * Created by Administrator on 2016/1/13.
 */
@Layout(R.layout.fragment_scrollable_tab)
public class HabitsTabFragment extends BaseFragment {
    private List<ScheduleEvent> scheduleEventList;
    private ArgbEvaluator argbEvaluator = new ArgbEvaluator();
    @Id(R.id.viewPager)
    private ViewPager viewPager;
    @Id(R.id.tabLayout)
    private TabLayout tabLayout;
    private ChartFragment chartFragment;


    private int curColor = Color.TRANSPARENT;


    private FragmentStatePagerAdapter adapter;
    private ViewPager.OnPageChangeListener onPageChangeListener = new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            if (!scheduleEventList.isEmpty() && getUserVisibleHint()) {
                int startColor = scheduleEventList.get(position).color;
                int nextPos = position + 1;
                if (nextPos == scheduleEventList.size()) {
                    nextPos--;
                }
                int endColor = scheduleEventList.get(nextPos).color;
                curColor = (int) argbEvaluator.evaluate(positionOffset, startColor, endColor);
                setUplayoutColor(curColor);
            }
        }

        @Override
        public void onPageSelected(int position) {
            chartFragment.updateCircleInfo(scheduleEventList.get(position));
        }

        @Override
        public void onPageScrollStateChanged(int state) {
        }
    };


    public ScheduleEvent getCurrent() {
        if (scheduleEventList.isEmpty()) {
            return null;
        } else {
            return scheduleEventList.get(viewPager.getCurrentItem());
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if(isVisibleToUser){
            setUplayoutColor(curColor);
        }
    }

    private void setUplayoutColor(int color) {
        if (null != tabLayout)
            tabLayout.setBackgroundColor(color);
        MainActivity context = (MainActivity) getActivity();
        if (null != context)
            context.setToolbarColor(color);
    }

    @Override
    protected void init(View rootView) {
        super.init(rootView);
        adapter = new FragmentStatePagerAdapter(getChildFragmentManager()) {
            @Override
            public void startUpdate(ViewGroup container) {
                viewPager.requestLayout();//解决HeadTabPagerWrappper 的 BUG 导致无法自动刷新问题
            }

            @Override
            public Fragment getItem(final int position) {
                return getFragment(position);
            }

            @Override
            public int getCount() {
                return scheduleEventList == null ? 0 : scheduleEventList.size();
            }

            @Override
            public CharSequence getPageTitle(int position) {
                return scheduleEventList.get(position).name;
            }

            @Override
            public int getItemPosition(Object object) {
                return POSITION_NONE;
            }
        };
        viewPager.setAdapter(adapter);
        tabLayout.setupWithViewPager(viewPager);
        viewPager.addOnPageChangeListener(onPageChangeListener);
        chartFragment = (ChartFragment) getChildFragmentManager().findFragmentById(R.id.circle_fragment);
    }

    private HashMap<Long, MonthViewFragment> cacheMap = new HashMap<>();

    @NonNull
    private Fragment getFragment(final int position) {
        ScheduleEvent scheduleEvent = scheduleEventList.get(position);
        MonthViewFragment monthViewFragment = cacheMap.get(scheduleEvent.id);
        if (null == monthViewFragment) {
            monthViewFragment = MonthViewFragment.newInstance(scheduleEvent, Calendar.getInstance().get(Calendar.YEAR), Calendar.getInstance().get(Calendar.MONTH));
            cacheMap.put(scheduleEvent.id, monthViewFragment);
        }else{
            monthViewFragment.freshData();
        }
        monthViewFragment.setOnDataChangedListener(new MonthViewFragment.OnDataChangedListener() {
            @Override
            public void onDataChanged() {
                chartFragment.updateCircleInfo(scheduleEventList.get(position));
            }
        });
        return monthViewFragment;
    }

    @Override
    public void onResume() {
        super.onResume();
        loadData();
    }

    private void loadData() {
        ScheduleEventDao.getRountineScheduleEvents(new SqlCallback<List<ScheduleEvent>>() {
            @Override
            public void onSucess(List<ScheduleEvent> scheduleEvents) {
                scheduleEventList = scheduleEvents;
                if (!scheduleEventList.isEmpty()) {
                    viewPager.setVisibility(View.VISIBLE);
                    tabLayout.setVisibility(View.VISIBLE);
                    adapter.notifyDataSetChanged();
                    ScheduleEvent curEvent = scheduleEventList.get(viewPager.getCurrentItem());
                    chartFragment.updateCircleInfo(curEvent);
                    curColor = curEvent.color;
                } else {
                    viewPager.setVisibility(View.GONE);
                    tabLayout.setVisibility(View.GONE);
                }
            }
        });
    }


    public static HabitsTabFragment newInstance() {
        return new HabitsTabFragment();
    }


    public void addHabbit(ScheduleEvent scheduleEvent) {
        scheduleEventList.add(0, scheduleEvent);
        viewPager.getAdapter().notifyDataSetChanged();
    }
}
